import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

import '../javascript_channel.dart';

class OnBack extends JavaScriptChannel {

  List<String> defaultUrls = [
    "id_card_authentication",
    "emergency_contacts",
    "personal_infomation",
    "review_tips",
    "add_bankcard",
    "confirm_borrow",
    "additionalInfomation"
  ];

  List<String> backUrls = [];

  @override
  List<String> get actions => ['getBackUrls'];

  @override
  onReceive(Map newMsg) {
    backUrls = newMsg['data']['urlArray'].cast<String>();
  }

  Future<bool> onBack(String homeUrl) async {
    String currentUrl = await webCtrl?.currentUrl() ?? "";
    String? matchUrl;
    String? matchNeedHomeUrl;

    for (var element in backUrls) {
      if (currentUrl.contains(element)) {
        matchUrl = element;
      }
    }

    debugPrint('currentUrl: $currentUrl');
    debugPrint('matchUrl: $matchUrl');
    // debugPrint('currentUrl path: ${Uri.parse(currentUrl).path}');

    if (matchUrl != null) {
      callBack(true, {'url': matchUrl});
      return false;
    }

    Uri currentUri = Uri.parse(currentUrl);
    debugPrint('currentUrl path: ${currentUri.path}');
    debugPrint('currentUrl fragment: ${currentUri.fragment}');

    if (currentUri.path == "/" && currentUri.fragment == '/') {
      // 主页
      SystemNavigator.pop();
      return false;
    } else {

      // 检测needHomeUrk
      for (var element in defaultUrls) {
        if (currentUrl.contains(element)) {
          matchNeedHomeUrl = element;
        }
      }

      debugPrint('matchNeedHomeUrl: ${matchNeedHomeUrl}');
      if (matchNeedHomeUrl != null) {
        webCtrl?.loadRequest(Uri.parse(homeUrl));
        return false;

      } else {
        // 走正常回退
        if (await webCtrl!.canGoBack()) {
          debugPrint('controller can go back');
          webCtrl?.goBack();
          return false;
        } else {
          return true;
        }
      }
    }
  }

}